package nsq_service

import (
	"encoding/json"
	"gin-swagger-demo/pkg/logging"
	"github.com/nsqio/go-nsq"
)

func StartProducer(address, topic string, msg []byte) error {
	cfg := nsq.NewConfig()
	producer, err := nsq.NewProducer(address, cfg)
	if err != nil {
		return err
	}
	if err := producer.Publish(topic, msg); err != nil {
		return err
	}
	if producer != nil {
		producer.Stop()
	}
	return nil
}

type NSQReq struct {
	Id int `json:"id"`
	Name string `json:"name"`
}

// ExampleStartProducer 生产示例
func ExampleStartProducer(){
	nsqReq := NSQReq{
		Id: 1,
		Name:"胡歌",
	}
	rst, _ := json.Marshal(nsqReq)
	address :="10.20.0.2:4150"
	topic :="examNsqTopic"
	if err := StartProducer(address,topic, rst); err != nil {
		logging.Error("ExampleStartProducer err",err)
	}
}
